package com.pxdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.pxdp.dto.Result;
import com.pxdp.entity.SeckillVoucher;
import com.pxdp.entity.VoucherOrder;
import com.pxdp.mapper.VoucherOrderMapper;
import com.pxdp.service.ISeckillVoucherService;
import com.pxdp.service.IVoucherOrderService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pxdp.utils.*;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.aop.framework.AopContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.connection.stream.*;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import java.time.Duration;
import java.time.LocalDateTime;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Slf4j
@Service
public class VoucherOrderServiceImpl extends ServiceImpl<VoucherOrderMapper, VoucherOrder> implements IVoucherOrderService {

    @Autowired
    private ISeckillVoucherService seckillVoucherService;

    @Autowired
    private RedisWorker redisWorker;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private RedissonClient redissonClient;

    private IVoucherOrderService proxy;
    /**
     * 使用spring自带的类加载lua脚本文件
     */
    private static final DefaultRedisScript<Long> SECKILL_SCRIPT ;
    //将加载类放到静态代码块中 启动项目时会跟着类一起加载，减少IO操作
    static{
        SECKILL_SCRIPT = new DefaultRedisScript<>();
        //设置脚本加载路径
        SECKILL_SCRIPT.setLocation(new ClassPathResource("seckill.lua"));
        //设置返回值类型
        SECKILL_SCRIPT.setResultType(Long.class);
    }

    //定义一个阻塞队列对象
    //private BlockingQueue<VoucherOrder> orderTasks = new ArrayBlockingQueue<>(1024 * 1024);
    //定义线程池 用来异步处理队列中的订单信息
    private static final ExecutorService SECKILL_EXECUTOR = Executors.newSingleThreadExecutor();

    //定义一个继承了runnable接口的内部类 来执行线程
    public class VoucherOrderHandler implements Runnable{
        @Override
        public void run() {
            //用死循环去不断的执行异步线程的方法
            log.info("死循环");
            while (true){
                try {
                    //获取消息队列中的订单信息
                    List<MapRecord<String, Object, Object>> list = stringRedisTemplate.opsForStream().read(
                            Consumer.from("g1", "c1"),
                            StreamReadOptions.empty().count(1).block(Duration.ofSeconds(2)),
                            StreamOffset.create("stream.orders", ReadOffset.lastConsumed())
                    );
                    //判断消息是否获取成功
                    if(list == null || list.isEmpty()) {
                        //如果失败说明没有消息 继续循环
                        continue;
                    }

                    //如果成功，才可以下单
                        //解析集合
                    MapRecord<String, Object, Object> entries = list.get(0);
                    Map<Object, Object> value = entries.getValue();
                    VoucherOrder voucherOrder = BeanUtil.fillBeanWithMap(value, new VoucherOrder(), true);
                    handleVoucherOrder(voucherOrder);
                    //确认消息队列中的消息
                    stringRedisTemplate.opsForStream().acknowledge("stream.orders","g1",entries.getId());

                } catch (Exception e) {
                    log.info("处理订单时发生异常:",e);
                    handlePendingList();
                }
            }
        }

        private void handlePendingList() {
            while (true){
                try {
                    //获取消息队列中的订单信息
                    List<MapRecord<String, Object, Object>> list = stringRedisTemplate.opsForStream().read(
                            Consumer.from("g1", "c1"),
                            StreamReadOptions.empty().count(1),
                            StreamOffset.create("stream.orders", ReadOffset.from("0"))
                    );
                    //判断消息是否获取成功
                    if(list == null || list.isEmpty()) {
                        //如果失败说明pending-list中没有异常 结束循环
                        break;
                    }

                    //如果成功，才可以下单
                    //解析集合
                    MapRecord<String, Object, Object> entries = list.get(0);
                    Map<Object, Object> value = entries.getValue();
                    VoucherOrder voucherOrder = BeanUtil.fillBeanWithMap(value, new VoucherOrder(), true);
                    handleVoucherOrder(voucherOrder);
                    //确认消息队列中的消息
                    stringRedisTemplate.opsForStream().acknowledge("stream.orders","g1",entries.getId());

                } catch (Exception e) {
                    log.info("处理pending-list时发生异常:",e);
                }
            }
        }
       /* public void run() {
            //用死循环去不断的执行异步线程的方法
            log.info("死循环");
            while (true){
                try {
                    //获取队列当中的信息
                    VoucherOrder voucherOrder = orderTasks.take();
                    //调用一个方法去创建订单
                    handleVoucherOrder(voucherOrder);

                } catch (InterruptedException e) {
                    log.info("处理订单时发生异常:",e);
                }

            }
        }*/


    }



    private void handleVoucherOrder(VoucherOrder voucherOrder) {
        log.info("添加到数据库方法");
        //获取用户id
        Long userId = voucherOrder.getUserId();
        //创建锁对象
        RLock lock = redissonClient.getLock("lock:order:" + userId);
        //获取锁
        boolean flag = lock.tryLock();
        if(!flag){
            log.info("不允许重复购买");
            return;
        }
        try {
            proxy.createVoucherOrder(voucherOrder);
        }finally {
            lock.unlock();
        }

    }
    //使用spring中提供的postConstruct注解 让项目启动时就执行这个方法
    @PostConstruct
    private void init(){
        log.info("执行初始化方法");
        SECKILL_EXECUTOR.submit(new VoucherOrderHandler());
    }


    @Override
    @Transactional
    public Result seckillVoucher(Long voucherId) {
        //获取用户id
        Long userId = UserHolder.getUser().getId();
        //获取订单id
        long orderId = redisWorker.nextId("order");
        //执行lua脚本
        Long result = stringRedisTemplate.execute(
                SECKILL_SCRIPT,
                Collections.emptyList(),
                voucherId.toString(), userId.toString(),String.valueOf(orderId)
        );

        //判断执行脚本之后的结果
        int value = result.intValue();

        if(value != 0){
            return Result.fail(value == 1 ? "库存不足":"不能重复购买");
        }
        //如果为0 代表有资格购买


        //获取代理对象
        proxy = (IVoucherOrderService) AopContext.currentProxy();
        return Result.ok(orderId);
    }



    //使用java的阻塞队列
   /* @Override
    @Transactional
    public Result seckillVoucher(Long voucherId) {
        Long userId = UserHolder.getUser().getId();

        //执行lua脚本
        Long result = stringRedisTemplate.execute(
                SECKILL_SCRIPT,
                Collections.emptyList(),
                voucherId.toString(), userId.toString()
        );

        //判断执行脚本之后的结果
        int value = result.intValue();

        if(value != 0){
            return Result.fail(value == 1 ? "库存不足":"不能重复购买");
        }
        //如果为0 代表有资格购买
        long orderId = redisWorker.nextId("order");

        VoucherOrder voucherOrder = new VoucherOrder();
        voucherOrder.setId(orderId);
        voucherOrder.setUserId(UserHolder.getUser().getId());
        voucherOrder.setVoucherId(voucherId);
        //将voucherOrder信息存入阻塞队列当中
        orderTasks.add(voucherOrder);
        //获取代理对象
        proxy = (IVoucherOrderService) AopContext.currentProxy();
        return Result.ok(orderId);
    }*/


   /* @Override
    @Transactional
    public Result seckillVoucher(Long voucherId) {

        //查询优惠券
        SeckillVoucher voucher = seckillVoucherService.getById(voucherId);

        //判断秒杀是否开始
        if (voucher.getBeginTime().isAfter(LocalDateTime.now())) {
            return Result.fail("活动还未开始");
        }
        if (voucher.getEndTime().isBefore(LocalDateTime.now())) {
            return Result.fail("活动已结束");
        }
        //判断库存是否充足
        if (voucher.getStock() < 1) {
            return Result.fail("库存不足");
        }
        Long userId = UserHolder.getUser().getId();
        //创建锁对象
        //SimpleRedisLock lock = new SimpleRedisLock(stringRedisTemplate,"order:"+userId);

        RLock lock = redissonClient.getLock("order:" + userId);
        //获取锁对象
        boolean isLock = lock.tryLock();
            //判断锁是否获取成功
        if(!isLock){
            return Result.fail("只能下单一次！！");
        }
        try {
            IVoucherOrderService proxy = (IVoucherOrderService) AopContext.currentProxy();
            return proxy.createVoucherOrder(voucherId);
        } finally{
            lock.unlock();
        }

    }*/


    public void createVoucherOrder(VoucherOrder voucherOrder){
        log.info("添加到数据库");
        //判断用户是否已经购买过
        Long userId = voucherOrder.getUserId();

        Integer count = query().eq("user_id", userId).eq("voucher_id", voucherOrder.getVoucherId()).count();
        if (count > 0) {
            log.error("已经购买过一次");
            return;
        }
        //扣减库存
        boolean flag = seckillVoucherService.update().setSql("stock = stock - 1").eq("voucher_id", voucherOrder.getVoucherId()).gt("stock", 0).update();
        if (!flag) {
           log.error("库存不足");
           return;
        }

        //创建订单
        save(voucherOrder);
    }
}
